import re
from dataclasses import dataclass


@dataclass
class DymolaResult:
    model_name: str
    simulation_end_time: float
    cpu_time_integration: float
    cpu_time_initialization: float
    result_points: int
    grid_points: int
    accepted_steps: int
    rejected_steps: int
    f_evaluations: int
    non_linear_iterations: int
    non_linear_failures: int
    jacobian_evaluations: int
    crossing_function_evaluations: int
    model_time_events: int
    state_events: int
    step_events: int
    maximum_integration_order: int


def parse_dymola_results(filepath):
    with open(filepath, 'r') as file:
        content = file.read()

    # Regex patterns to extract data
    model_pattern = r"Model: (.+)"
    end_time_pattern = r"Integration terminated successfully at T = (\d+)"
    cpu_integration_pattern = r"CPU-time for integration\s+: ([\d\.]+) seconds"
    cpu_initialization_pattern = r"CPU-time for initialization\s+: ([\d\.]+) seconds"
    results_pattern = {
        "result_points": r"Number of result points\s+: (\d+)",
        "grid_points": r"Number of grid points\s+: (\d+)",
        "accepted_steps": r"Number of accepted steps\s+: (\d+)",
        "rejected_steps": r"Number of rejected steps\s+: (\d+)",
        "f_evaluations": r"Number of f-evaluations \(dynamics\)\s+: (\d+)",
        "non_linear_iterations": r"Number of non-linear iteration\s+: (\d+)",
        "non_linear_failures": r"Number of non-linear convergence failures\s+: (\d+)",
        "jacobian_evaluations": r"Number of Jacobian-evaluations\s+: (\d+)",
        "crossing_function_evaluations": r"Number of crossing function evaluations\s+: (\d+)",
        "model_time_events": r"Number of model time events\s+: (\d+)",
        "state_events": r"Number of state events\s+: (\d+)",
        "step_events": r"Number of step events\s+: (\d+)",
        "maximum_integration_order": r"Maximum integration order\s+: (\d+)"
    }

    # Extract data using regex
    model_name = re.search(model_pattern, content).group(1)
    end_time = float(re.search(end_time_pattern, content).group(1))
    cpu_integration = float(re.search(cpu_integration_pattern, content).group(1))
    cpu_initialization = float(re.search(cpu_initialization_pattern, content).group(1))

    results = {key: int(re.search(pattern, content).group(1)) for key, pattern in results_pattern.items()}

    return DymolaResult(
        model_name=model_name,
        simulation_end_time=end_time,
        cpu_time_integration=cpu_integration,
        cpu_time_initialization=cpu_initialization,
        **results
    )


# Example Usage
if __name__ == "__main__":
    result_file_path = r"D:\pyProject\dymola_test\dymola_test\dymola_res\Modelica.Blocks.Examples.SlewRateLimiter_500.txt"
    result = parse_dymola_results(result_file_path)
    print(result)
